<template>
  <div class="books-page">
    <div class="header">
      <h1>齐大图书商城 · 图书列表</h1>
      <div class="header-actions">
        <el-button type="success" @click="goCenter">个人中心</el-button>
        <el-button @click="goLogin">登录</el-button>
        <el-button @click="goRegister">注册</el-button>
      </div>
    </div>

    <el-card class="card" shadow="hover">
      <el-form :inline="true" :model="query" class="filter-form">
        <el-form-item label="关键词">
          <el-input v-model="query.keyword" placeholder="输入关键词" clearable @keyup.enter="loadBooks" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="query.category_id" placeholder="选择分类" clearable style="width: 180px">
            <el-option label="全部" :value="undefined" />
            <el-option label="文学" :value="1" />
            <el-option label="科技" :value="2" />
            <el-option label="少儿" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadBooks" :loading="loading">搜索</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="books" border style="width: 100%" @row-click="goDetail">
        <el-table-column type="index" label="#" width="60" />
        <el-table-column label="封面" width="100">
          <template #default="{ row }">
            <el-image
              :src="row.cover_image"
              fit="cover"
              style="width: 56px; height: 70px; border-radius: 4px;"
              :preview-src-list="row.cover_image ? [row.cover_image] : []"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="书名" min-width="160" />
        <el-table-column prop="author" label="作者" width="140" />
        <el-table-column prop="publisher" label="出版社" width="160" />
        <el-table-column label="价格" width="100">
          <template #default="{ row }">
            <span>¥ {{ formatPrice(row.price) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column label="描述" min-width="240">
          <template #default="{ row }">
            <span class="desc-ellipsis">{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click.stop="goDetail(row)">详情</el-button>
            <el-button size="small" @click.stop="handleAddToCart(row)">加入购物车</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pager">
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="query.size"
          :current-page="query.page"
          @current-change="onPageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { fetchBooks, addToCart } from '@/api/book'

const router = useRouter()

const loading = ref(false)
const books = ref<any[]>([])
const total = ref(0)

// 开发环境本地测试数据
const SAMPLE_BOOKS = [
  {
    book_id: 1,
    title: '深入理解计算机系统',
    author: 'Randal E. Bryant',
    publisher: '机械工业出版社',
    price: 129.00,
    description: '从程序到机器的全景式解读，计算机系统经典之作。',
    cover_image: 'https://dummyimage.com/280x360/ccd/333&text=CSAPP',
    category: '科技'
  },
  {
    book_id: 2,
    title: '三体',
    author: '刘慈欣',
    publisher: '重庆出版社',
    price: 68.00,
    description: '宏大的科幻世界观，震撼的文明史诗。',
    cover_image: 'https://dummyimage.com/280x360/bcd/333&text=Three-Body',
    category: '文学'
  },
  {
    book_id: 3,
    title: '小王子',
    author: '圣-埃克苏佩里',
    publisher: '人民文学出版社',
    price: 35.00,
    description: '写给大人的童话，关于爱与成长的寓言。',
    cover_image: 'https://dummyimage.com/280x360/abc/333&text=Little+Prince',
    category: '少儿'
  },
  {
    book_id: 4,
    title: '设计模式',
    author: 'Erich Gamma 等',
    publisher: '机械工业出版社',
    price: 99.00,
    description: '可复用面向对象软件的基础，23种经典模式。',
    cover_image: 'https://dummyimage.com/280x360/cde/333&text=Design+Patterns',
    category: '科技'
  }
]

const query = reactive<{ page: number; size: number; category_id?: number; keyword?: string }>({
  page: 1,
  size: 10,
  category_id: undefined,
  keyword: ''
})

const loadBooks = async () => {
  try {
    loading.value = true
    const res = await fetchBooks(query)
    const data = res.data || {}
    const list = Array.isArray(data.book_list) ? data.book_list : (Array.isArray(data) ? data : [])
    // 如果后端暂无数据，使用本地测试数据
    if (!list.length && !query.keyword) {
      books.value = SAMPLE_BOOKS
      total.value = SAMPLE_BOOKS.length
    } else {
      books.value = list
      total.value = Number(data.total || list.length || 0)
    }
  } catch (e: any) {
    // 出错时回退到本地测试数据
    books.value = SAMPLE_BOOKS
    total.value = SAMPLE_BOOKS.length
    ElMessage.warning('已加载本地测试数据')
  } finally {
    loading.value = false
  }
}

const onPageChange = (p: number) => {
  query.page = p
  loadBooks()
}

const reset = () => {
  query.page = 1
  query.size = 10
  query.category_id = undefined
  query.keyword = ''
  loadBooks()
}

const goDetail = (row: any) => {
  router.push(`/books/${row.book_id || row.id}`)
}

const formatPrice = (p: any) => {
  const n = Number(p)
  if (Number.isNaN(n)) return '-'
  return n.toFixed(2)
}

const handleAddToCart = async (row: any) => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      router.push({ path: '/login', query: { redirect: '/books' } })
      return
    }
    await addToCart({ book_id: row.book_id || row.id, quantity: 1 })
    ElMessage.success('已加入购物车')
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '加入购物车失败')
  }
}

const goCenter = () => {
  router.push('/center')
}

const goLogin = () => {
  router.push('/login')
}

const goRegister = () => {
  router.push('/register')
}

onMounted(() => {
  loadBooks()
})
</script>

<style scoped>
.books-page { padding: 20px; }
.header { margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between; }
.header-actions { display: flex; gap: 8px; }
.card { }
.filter-form { margin-bottom: 12px; }
.pager { margin-top: 12px; text-align: right; }
.desc-ellipsis {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
